package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.Yeast;

public class YeastPresenter extends AbstractPresenter<Yeast> {
	final String SINGLEITEM = "yeast";
	final String MULTIITEM = "yeasts";
	
	public ArrayList<Yeast> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public Yeast tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public Yeast tryJSONParseNoHeader(String input){
		try{
			JSONObject jsonHop = new JSONObject(input);
			Yeast item = createItemFromJSONObject(jsonHop);
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Yeast createItemFromJSONObject(JSONObject jsonObject){
		Yeast item = new Yeast();
		try{
			item.setYeastID(jsonObject.getInt("yid"));
			item.setMaxGen(jsonObject.getInt("maxGen"));
			item.setYeastActive(jsonObject.getBoolean("yeastActive"));
			item.setYeastAdditionalPitchRate(jsonObject.getDouble("yeastAdditionalPitchRate"));
			item.setYeastBasePitchRate(jsonObject.getDouble("yeastBasePitchRate"));
			item.setYeastCost(jsonObject.getDouble("yeastCost"));
			item.setYeastOrderVolume(jsonObject.getDouble("yeastOrderVol"));
			item.setYeastDesc(jsonObject.getString("yeastDesc"));
			item.setYeastName(jsonObject.getString("yeastName"));
			
			final StockCodePresenter presenter = new StockCodePresenter();
			JSONObject jsonSC = jsonObject.getJSONObject("stockCode");
			item.setStockCode(presenter.createItemFromJSONObject(jsonSC));
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Yeast item){
		try{
			JSONObject json = new JSONObject();
			json.put("yid", item.getYeastID());
			json.put("maxGen", item.getMaxGen());
			json.put("yeastActive", item.isYeastActive());
			json.put("yeastAdditionalPitchRate", item.getYeastAdditionalPitchRate());
			json.put("yeastBasePitchRate", item.getYeastBasePitchRate());
			json.put("yeastCost", item.getYeastCost());
			json.put("yeastOrderVol", item.getYeastOrderVolume());
			json.put("yeastDesc", item.getYeastDesc());
			json.put("yeastName", item.getYeastName());
			
			if(item.getStockCode()!=null){
				final StockCodePresenter presenter = new StockCodePresenter();
				json.put("stockCode", presenter.createJSON(item.getStockCode()));
			} else {
				json.put("stockCode", JSONObject.NULL);
			}

			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Yeast getEmptyEntity(){
		Yeast entity = new Yeast();
		return entity;
	}
}
